package com.wehealth.three.lib_connect.device.bluetoothdevice.kdevice

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import androidx.lifecycle.LiveData
import com.wehealth.three.lib_connect.device.usbdevice.data.ParseOriginEcgData

/***
 * @author 栾桂明
 * @date 2023年11月24
 * @desc 蓝牙通用功能定义
 */
abstract class BlueToothHelper(val context: Activity) {
// 28E9  10473    18a   394
    companion object {
        //扫描的设备的名称
        const val SCAN_CLASSIC_DEVICE_NAME = "WWKECG"
        const val SCAN_BLE_DEVICE_NAME = "WWKECG12E"

        //扫描的时间
        val SCAN_PERIOD: Long = 5000
    }

    //当前设备是否支持蓝牙
    var btIsoSupport = true

    //蓝牙是否已经打开
    var btIsEnable = false

    private val bluetoothManager = context.getSystemService(BluetoothManager::class.java)

    val bluetoothAdapter = bluetoothManager.adapter

    /***
     * 判断是否支持蓝牙，不支持的时候执行action中的逻辑
     * 终止后续的操作
     */
    fun isSupportBT(action: () -> Unit) {
        btIsoSupport = if (bluetoothAdapter == null) {
            action.invoke()
            false
        } else {
            true
        }
    }


    /***
     * 是否是五维康的设备
     */
    @SuppressLint("MissingPermission")
    fun isWeHealthDevice(device: String, isBle: Boolean) =
        if (isBle) {
            device == SCAN_BLE_DEVICE_NAME
        } else {
            device == SCAN_CLASSIC_DEVICE_NAME
        }


    /***
     * 判断蓝牙是否可用，不可以通过action指定操作提示
     */
    fun isEnableBT(action: () -> Unit) {
        if (btIsoSupport) {
            when {
                bluetoothAdapter.isEnabled -> {
                    btIsEnable = true
                }

                !bluetoothAdapter.isEnabled -> {
                    btIsEnable = false
                    //设备蓝牙未开启
                    action.invoke()
                }
            }
        }

    }


    abstract fun discoverDevice()

    abstract fun stopDiscoverDevice()


    abstract fun connectDevice(
        device: BluetoothDevice,
        ecgDataGetListener: ParseOriginEcgData.EcgDataGetListener
    ): LiveData<String>


}